/*
 * @Author: yudun yudun@idata.ah.cn
 * @Date: 2025-09-28 11:29:00
 * @LastEditors: yudun yudun@idata.ah.cn
 * @LastEditTime: 2025-09-28 14:18:20
 * @FilePath: \trae-code\spzx-admin\src\utils\axios.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from "axios";
// 假设 store 模块在 src/store/index.ts，根据实际项目结构调整路径
import { useUserStore } from "../stores/index.ts";
import { getToken } from "./auth";
import router from "../router/index.ts";

console.log("import.meta.env=", import.meta.env);

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (useUserStore().token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers["X-Token"] = getToken();
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.

    // 添加放行导出接口逻辑
    // 通过返回数据是不是blob类型来判断是否是导出接口
    if (res instanceof Blob) {
      return res;
    }
    
    if (res.code !== 200) {
      // 208 用户未登录
      if (res.code == 208) {
        sessionStorage.clear()
        const redirect = encodeURIComponent(window.location.href); // 当前地址栏
        
        // 由于找不到 router，需要先导入 vue-router 实例
        // 假设 router 模块在 src/router/index.ts，根据实际项目结构调整路径
        
        router.push(`/login?redirect=${redirect}`);
        return Promise.reject(new Error(res.message || "用户未登录"));
      }

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        ElMessageBox.confirm(
          "You have been logged out, you can cancel to stay on this page, or log in again",
          "Confirm logout",
          {
            confirmButtonText: "Re-Login",
            cancelButtonText: "Cancel",
            type: "warning",
          }
        ).then(() => {
          // 根据报错信息，useUserStore 上不存在 resetToken 方法，推测可能需要调用清除 token 的其他方法
          // 此处假设清除 token 的方法是 removeToken，可根据实际情况修改
          // useUserStore().removeToken();
          location.reload();
        });
      }

      ElMessage({
        message: res.message || "Error",
        type: "error",
        duration: 5 * 1000,
      });
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    console.log("err" + error); // for debug
    ElMessage({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
